﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using LynxWebLog;

namespace LynxWebLog.Controllers
{
    public class ChooseBlogController : Controller
    {
        //
        // GET: /ChooseBlog/
        [Authorize(Roles="BlogUser,BlogAdmin")]
        public async Task<ActionResult> Index(string returnUrl)
        {
            HttpClient client = ClientUtility.BlogAPIClient();
            HttpResponseMessage resp = await client.GetAsync("api/BlogData/?filter=username eq '" + User.Identity.Name + "'");
            resp.EnsureSuccessStatusCode();

            List<BlogData> lbd = (await resp.Content.ReadAsAsync<IEnumerable<BlogData>>()).ToList();
            List<SelectListItem> selList = new List<SelectListItem>();
            foreach (BlogData item in lbd) {
                selList.Add(new SelectListItem() { Value = item.blogname, Text = item.blogname });
            }
            ViewBag.BlogDataList = selList;
            ViewBag.ReturnUrl = returnUrl;

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult BlogSelected(string blogName, string returnUrl)
        {
            CookieFacade.CurrentBlog = blogName;
            if (Url.IsLocalUrl(returnUrl)) {
                return Redirect(returnUrl);
            } else {
                return RedirectToAction("Index", "Home");
            }
        }
	}
}